<template>
  <div class="sub-popup">
    <van-search
    ref="cf"
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
      @cancel="onCancel"
      @clear="onClear"
    />
    <down-list v-if="blockShow == 1" :list="listArr"></down-list>
    <history-hot
      v-else-if="blockShow == 2"
      :historyarr="historyArr"
      :value="value"
      :hotarr="hotArr"
      @setneiku = "getneiku"
    ></history-hot>
    <product v-else></product>
  </div>
</template>

<script>
/*
  唯一会出现Product区块的情况：执行搜索的时候
  历史区块的出现情况：
    1、刚进popup时，要显示HistoryHot
    2、只要搜索框中没有文字，就显示HistoryHot
  出现下拉列表区块的情况：只要当前正在输入中，就应该出现DownList
*/
import { GetPopupData, GetDownListData } from "@/request/api";
import DownList from "@/components/subPopup/DownList";
import HistoryHot from "@/components/subPopup/HistoryHot";
import Product from "@/components/subPopup/Product";
export default {
  data() {
    return {
      value: "",
      blockShow: 2, // 1代表DownList，2代表HistoryHot，其他情况都是代表Product
      historyArr: [], // 历史记录数组
      hotArr: [], // 热门搜索数组
      listArr: [] // 传递给DownList组件的数组
    };
  },
  components: {
    DownList,
    HistoryHot,
    Product
  },
  watch: {
    // 监听输入框的值变动
    value(val) {
      if (val == "") {
        // 显示HistoryHot区块
        this.blockShow = 2;
      }
    }
  },
  methods: {
     getneiku(val) {
      this.blockShow = val
    },
    // 执行搜索命令
    onSearch(val) {
       // 输入的排除kongzhi
      this.value = val.replace(/(^\s*) | (\s*$)/g,'')
      // 显示Product区块
      this.blockShow = 3;
      this.$store.dispatch("AsyncChangeProductArr", { keyword: this.value });
    },
    // 点击取消
    onCancel() {
      // 显示HistoryHot区块
      // this.$store.state.isClose = false
      this.blockShow = 2;
      // 调用mutations中的controlPopupShow
      this.$store.commit("controlPopupShow", false);
    },
    // 输入时
    onInput() {
      // 显示DownList区块
      this.blockShow = 1;
      GetDownListData({
        keyword: this.value
      }).then(res => {
        if (res.errno == 0) {
          console.log(res.data);
          this.listArr = res.data;
        }
      });
    },
    // 清除文字时
    onClear() {
      // 显示HistoryHot区块
      this.blockShow = 2;
    }
  },
  created() {
    this.$nextTick(()=>{
      console.log(this.$refs.cf)
    })
    GetPopupData().then(res => {
      if (res.errno == 0) {
        this.value = res.data.defaultKeyword.keyword;
        this.historyArr = res.data.historyKeywordList;
        this.hotArr = res.data.hotKeywordList;
      }
    });
  }
};
</script>

<style>
</style>